<template>
  <el-dialog
  :title="title"
  :visible.sync="visible"
  width="40%"
  :before-close="handleClose">
    <el-form label-width="100px" class="demo-ruleForm" style="width:90%" v-loading="loading">
        <!--data 数据集合，
            default-checked-keys 默认勾选
            props node-key 每个树节点用来作为唯一标识的属性 
            show-checkbox 显示勾选框 
            accordion 每次只打开一个同级树节点展开 highlight-current 高亮当前选中节点 -->
        <el-tree
            ref="tree"
            :props="props"
            :data="menuList"            
            node-key="id"
            show-checkbox
            accordion
            highlight-current
            :default-checked-keys="menuIds">
        </el-tree>

        <el-form-item>
            <el-button type="primary" size="mini" @click="submitForm">确定</el-button>
            <el-button @click="handleClose" size="mini">取消</el-button>
        </el-form-item>
    </el-form>
    </el-dialog>
</template>

<script>
import menuApi from '@/api/menu' 
import roleApi from '@/api/role'   
export default {
    data() {
        return {
            props: {
                label: 'name',
                children: 'children',
                
            },
            loading: false, // 加载中 
            menuList: [], // 所有菜单集合 
            menuIds: [] // 角色拥有的权限菜单ids
        }
    },
    props:{
        roleId: null, // 角色id
        visible:{
            type:Boolean,
            default:false
        },
        title:{
            type:String,
            default:''
        },
        remoteClose: Function 
    },
    watch:{
        visible:function(val){
            if(val){
                this.getMenuList()
            }
        }
    },
    methods: {
        // 关闭窗口
        handleClose(){
            this.menuIds = [] 
            this.menuList = []
            this.remoteClose()
        },
        submitForm(){                        
            roleApi.saveRoleMenu(this.roleId,this.$refs.tree.getCheckedKeys()).then(response=>{
                if (response.code === 20000){
                this.$message({
                    message: '权限分配成功',
                    type: 'success'
                    });
                this.handleClose()
                
            }else{
                this.$message({
                    message: '权限分配失败',
                    type: 'error'
                    });
            }
            })
        },
        // 查询所有菜单
        getMenuList(){
            this.loading = true
            menuApi.getList({}).then(
                response=>{
                    this.menuList=response.data
                    this.getMenuIdsByRoleId()
                }
            )
            this.loading = false
        },
        getMenuIdsByRoleId(){
            roleApi.getMenuIdsByRoleId(this.roleId).then(
                response=>{
                    this.menuIds=response.data
                }
            )
        }
    },
}
</script>

<style>

</style>